package com.zyl.wechar.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zyl.wechar.bean.RequestBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//@RestController
@Controller
@RequestMapping("/wx")
public class WecharController {
    private static final Logger logger = LoggerFactory.getLogger(WecharController.class);

    @Resource
    private RestTemplate restTemplate;

    private String seesionKey = null;

    @Value("${secret}")
    private String secret;
    @Value("${appid}")
    private String appid;

    @GetMapping("/getData3")
    public Object getData3(@RequestParam RequestBean requestBean) {
        return requestBean.getCode();
    }

    @GetMapping("/getData")
    @ResponseBody
    public Object getData(HttpServletRequest request,
                          RedirectAttributes attr,
                          Model modelAndView) {
        logger.debug("into getData api");
        final RequestBean requestBean = new RequestBean();
        requestBean.setCode("200");
        return requestBean;
    }

    @PostMapping("/redirect")
    public String Redirect(RedirectAttributes attr, HttpServletResponse response) throws IOException {
        attr.addAttribute("username", "张三");
        attr.addFlashAttribute("username2", "张三2");
        return "redirect:/wx/getData";
    }

    @PostMapping("/login")
    @ResponseBody
    public Object login(@RequestBody String code) {
        String format = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appid, secret, code);

        ResponseEntity<String> forEntity = restTemplate.getForEntity(format, String.class);
        JSONObject jsonObject = null;
        if (forEntity.getStatusCode().is2xxSuccessful()) {
             jsonObject = JSONUtil.parseObj(forEntity.getBody());
        }
        if (jsonObject != null) {
            Object openid = jsonObject.get("openid");
            Object session_key = jsonObject.get("session_key");
            if (seesionKey == null) {
                seesionKey = session_key.toString();
            } else {
                if (seesionKey.equals(session_key)) {
                    logger.debug("两次session_key是相同的");
                }
            }
        }
        logger.debug(code);
        return "code";
    }
}
